package cn.kgc.common.advice;

import cn.kgc.common.constant.ResultConstant;
import cn.kgc.common.util.HttpException;
import cn.kgc.common.vo.Result;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author kgc
 * 控制器的异常处理
 */
//@ControllerAdvice("cn.kgc")
public class ExceptionAdvice {

    @ExceptionHandler(value = HttpException.class)
    public ResponseEntity  handleHttpException(HttpException httpException){
        HttpStatus httpStatus=HttpStatus.OK;
        //将异常信息封装到 Result对象中
        Result result= Result.builder()
                .code(httpException.getCode())
                .message(httpException.getMessage())
                .build();
        //响应头: 返回的数据格式
        HttpHeaders headers=new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //封装返回的响应实体
        ResponseEntity responseEntity=new ResponseEntity(result,headers,httpStatus);
        return responseEntity;
    }

    /**
     * spring security异常
     * @param accessDeniedException
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public Result error(AccessDeniedException accessDeniedException) throws AccessDeniedException{
        return Result.builder().code(ResultConstant.NO_PERMISSION.getCode())
                .message(ResultConstant.NO_PERMISSION.getMessage())
                .build();
    }


    @ExceptionHandler(value = Exception.class)
    public ResponseEntity  handleException(Exception exception){
        HttpStatus httpStatus=HttpStatus.OK;
        int code= ResultConstant.ERROR.getCode();
        String message=ResultConstant.ERROR.getMessage();
        //将异常信息封装到 Result对象中
        Result result= Result.builder().code(code).message(message).build();
        //响应头: 返回的数据格式
        HttpHeaders headers=new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //封装返回的响应实体
        ResponseEntity responseEntity=new ResponseEntity(result,headers,httpStatus);
        return responseEntity;
    }

}